package org.sg20.searchengine.sort;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.sg20.searchengine.search.SearchDriver;
import org.sg20.searchengine.search.SearchMapper;
import org.sg20.searchengine.search.SearchReducer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;

public class SortDriver {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException, URISyntaxException {
        //set up configuration for mapreduce job
        Configuration conf = new Configuration();

        //Parse arguments
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        if (otherArgs.length != 2) {
            System.err.println("Please input: xxx.jar SortDriver [InputPath] [OutputPath].");
            System.exit(1);
        }

        Job job = Job.getInstance(conf, "Sort");

        job.setJarByClass(SortDriver.class);
        job.setMapperClass(SortMapper.class);
        job.setReducerClass(SortReducer.class);

        job.setMapOutputKeyClass(TextReverse.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputKeyClass(TextReverse.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
        FileSystem fs = FileSystem.get(conf);

        String outpath = otherArgs[1] + "/MRSortRes";
        if (fs.exists(new Path(outpath)))
            fs.delete(new Path(outpath), true);
        FileOutputFormat.setOutputPath(job, new Path(outpath));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
